module UpgradesHelper
  def log_timestamp
    Time.now.iso8601
  end
  
  def log_fmt_timestamp(time)
    [(time/3600).to_i, (time/60 % 60).to_i, (time % 60).to_i].map{|t| t.to_s.rjust(2,'0')}.join(':')
  end
  
  # create or delete the process semaphore
  def upgrade_semaphore_deal(create = true)
    semaphore_file = File.join(RAILS_ROOT, "log/upgrade.semaphore")
    unless create
      File.delete(semaphore_file) if File.exists?(semaphore_file)
      return true
    end
    can_create = true
    if File.exists?(semaphore_file)
      timestamp = nil
      File.open(semaphore_file, 'r') { |f| timestamp = YAML.load(f.gets) }
      can_create = (Time.now - timestamp) / 3600 >= 1.0
    end
    File.open( semaphore_file, 'w' ) { |f| f.write Time.now.to_yaml } if can_create
    can_create
  rescue => e
    logger.error "Couldn't create semaphore file", e
    false
  end

  def upgrade_delete_log
    # reset and starts log file
    log_file = File.join(RAILS_ROOT, 'log/upgrade.log')
    File.delete(log_file) if File.exists?(log_file) && $SYNC_CONFIG[:wipe_log]
    log_file
  end
end